/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package info.touret.winecellar.servlet;

import info.touret.winecellar.reminder.ReminderModule;
import info.touret.winecellar.userinfo.server.domain.UserInfo;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.GeneralSecurityException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;
import com.google.inject.Guice;
import com.google.inject.Injector;

/**
 * 
 * @author touret-a
 */
public class TokenServlet extends HttpServlet {

	private static final Logger trace = Logger.getLogger(TokenServlet.class
			.getName());

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String tokenParameter = req.getParameter("token");
		if (tokenParameter == null) {
			// TODO a corriger
			req.getRequestDispatcher("/faces/retreiveToken.xhtml").forward(req,
					resp);
		} else {
			try {
				String onetimeUseToken = AuthSubUtil.getTokenFromReply(req
						.getQueryString());
				onetimeUseToken = URLDecoder.decode(onetimeUseToken, "UTF-8");
				String sessionToken = AuthSubUtil.exchangeForSessionToken(
						onetimeUseToken, null);
				trace.info("Récupération du token google :"+sessionToken);
				// todo a ameliorer
				UserService userservice = UserServiceFactory.getUserService();
				User user = userservice.getCurrentUser();
				UserInfo userinfo = UserInfo.findCurrentUserInApp(user);
				userinfo.setGdatatoken(sessionToken);
				trace.log(Level.INFO, "UTILISATEUR RECUPERE :{0}", user);
				userinfo.persist();
				trace.log(Level.WARNING,
						"Assignation du token effectue pour :{0}", user);
				//req.getSession().setAttribute("token", sessionToken);
				resp.sendRedirect("/Winecellar.html");
			} catch (GeneralSecurityException ex) {
				trace.log(Level.SEVERE, null, ex);
				throw new ServletException(ex);
			} catch (AuthenticationException ex) {
				trace.log(Level.SEVERE, null, ex);
				throw new ServletException(ex);
			}
		}
	}
}
